﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Tools
{
    public class OrderNumberHelper
    {
        static int ORDER_SCALE = 36;

        public static string GetOrderNo(DateTime dt, string phoneNumber)
        {
            if (dt < new DateTime(2000, 1, 1) || dt > new DateTime(2100, 1, 1) || phoneNumber.Length != 11)
            {
                throw new ArgumentException();
            }
            TimeSpan span = dt - new DateTime(2000, 1, 1);
            long t = ((long)(span.Days) * 24 * 3600 * 1000) + (long)(span.Hours) * 3600 * 1000 + (long)span.Minutes * 60 * 1000
                    + (long)span.Seconds * 1000 + (long)span.Milliseconds;
            string time = Extensions.ComplexString(t, ORDER_SCALE, 9);
            long phoneNum = Convert.ToInt64(phoneNumber);
            string phone = Extensions.ComplexString(phoneNum, ORDER_SCALE, 7);
            return "MO" + time + phone;
        }

        public static bool GetOrderInfo(string OrderNo, out DateTime time, out string phoneNumber)
        {
            if (OrderNo.StartsWith("MO") == false)
            {
                time = DateTime.MinValue;
                phoneNumber = "";
                return false;
            }
            time = new DateTime();
            string stime = OrderNo.Substring(2, 9);
            string sphone = OrderNo.Substring(11, 7);
            long ltime = Extensions.ComplexNumeric(stime, ORDER_SCALE);
            int days = (int)(ltime / (24 * 3600 * 1000));
            long dRemain = ltime % (24 * 3600 * 1000);
            int hours = (int)(dRemain / (3600 * 1000));
            long hRemain = dRemain % (3600 * 1000);
            int min = (int)(hRemain / (60 * 1000));
            long mRemain = hRemain % (60 * 1000);
            int sec = (int)(mRemain / 1000);
            int sRemain = (int)(mRemain % 1000);
            if (days < 0 || days > 100 * 365)
            {
                time = DateTime.MinValue;
                phoneNumber = "";
                return false;
            }
            DateTime t = new DateTime(2000, 1, 1);
            time = t.AddDays(days);
            time = time.AddHours(hours);
            time = time.AddMinutes(min);
            time = time.AddSeconds(sec);
            time = time.AddMilliseconds(sRemain);
            long phoneNum = Extensions.ComplexNumeric(sphone, ORDER_SCALE);
            phoneNumber = phoneNum.ToString();
            if (phoneNumber.Length != 11)
            {
                time = DateTime.MinValue;
                phoneNumber = "";
                return false;
            }
            return true;
        }

    }
}
